package com.yayo.mangement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yayo.mangement.utils.SaltEncryptionUtils;
import com.yayo.mangement.utils.StringUtils;
import com.yayo.mangement.dao.SysUserDao;
import com.yayo.mangement.model.SysUser;
import com.yayo.mangement.service.SysUserService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {

    @Override
    public Boolean update(SysUser sysUser) {
        if(StringUtils.isNotBlank(sysUser.getUserPassword())){
            String salt = SaltEncryptionUtils.getRandomSalt();
            String password = SaltEncryptionUtils.encryption(sysUser.getUserPassword(),salt);
            sysUser.setUserSalt(salt);
            sysUser.setUserPassword(password);
        }
        return baseMapper.updateById(sysUser) > 0;
    }

    @Override
    public SysUser findById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public SysUser findByUsername(String username) {
        LambdaQueryWrapper<SysUser> query = Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUserLoginName, username);
        SysUser sysUser = baseMapper.selectOne(query);
        return sysUser;
    }

    @Override
    public List<SysUser> findAll() {
        return baseMapper.selectList(null);
    }

    @Override
    public IPage<SysUser> paging(Page<SysUser> page, SysUser sysUser) {
        LambdaQueryWrapper query = Wrappers.<SysUser>lambdaQuery()
                .select(SysUser::getUserId,SysUser::getTenantId, SysUser::getUserName,
                        SysUser::getUserLoginName,SysUser::getUserPic,SysUser::getUserMobile,
                        SysUser::getCreatedAt,SysUser::getCreatedBy,SysUser::getUserEMail,
                        SysUser::getUserLastLogin,SysUser::getCreatedBy)
                .eq(SysUser::getDeleted, 0);
        return super.page(page, query);
    }

    @Override
    public void delete(List<Long> ids) {
        super.removeByIds(ids);
    }
}
